/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  LeaderAssignActivity.java   
 * @Package com.jiyi.activity.leader   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-23 上午10:37:18   
 * @version V1.0     
 */
package com.jiyi.activity.leader;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.leader.repair.LeaderMaintenanceRepairListActivity;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.owner.OwnerBean;
import com.jiyi.bean.weibao.DistributePersonBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.jiyi.widget.DropEditText;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: LeaderAssignActivity
 * @Description:TODO(主管派发)
 * @author: HYM
 * @date: 2017-9-23 上午10:37:18
 * 
 */
public class LeaderAssignActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.llWb)
	LinearLayout llWb;
	@BindView(R.id.tvCheckWb)
	TextView tvCheckWb;
	@BindView(R.id.ivCheckWb)
	ImageView ivCheckWb;

	@BindView(R.id.llWx)
	LinearLayout llWx;
	@BindView(R.id.tvCheckWx)
	TextView tvCheckWx;
	@BindView(R.id.ivCheckWx)
	ImageView ivCheckWx;

	@BindView(R.id.et_start)
	EditText et_start;
	@BindView(R.id.det_repairer)
	DropEditText det_repairer;
	@BindView(R.id.det_owner)
	DropEditText det_owner;
	@BindView(R.id.et_remark)
	EditText et_remark;

	/* 功能变量 */
	CommonAdapter<DistributePersonBean> distributerAdapter;
	CommonAdapter<DistributePersonBean> distributerAutoAdapter;
	private List<DistributePersonBean> distributer_list = new ArrayList<DistributePersonBean>();
	private List<DistributePersonBean> distributer_auto = new ArrayList<DistributePersonBean>();

	CommonAdapter<OwnerBean> companyAdapter;
	CommonAdapter<OwnerBean> companyAutoAdapter;
	private List<OwnerBean> company_list = new ArrayList<OwnerBean>();
	private List<OwnerBean> company_auto = new ArrayList<OwnerBean>();

	// 派发的任务类别 1 维保 2 维修
	int type = 1;

	// 加载进度圈
	Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leader_assign);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		setTop();
		setViewStatus();
		setAdater();
		checkType();
		getRepairerData("");
		getOwnerData("");
	}

	private void setTop() {
		tvBack.setText("");
		tvTitle.setText("任务派发");
		tvSearch.setVisibility(View.GONE);
	}

	private void setViewStatus() {
		et_start.setKeyListener(null);

		// 设置输入必填检测提示
		det_repairer.setTag(R.id.tag_view_empty, "派发对象不能为空");
		det_owner.setTag(R.id.tag_view_empty, "业主单位不能为空");
		et_start.setTag(R.id.tag_view_empty, "开始时间不能为空");
	}

	private void setAdater() {
		distributerAdapter = new CommonAdapter<DistributePersonBean>(this,
				distributer_list, R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, DistributePersonBean t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		distributerAutoAdapter = new CommonAdapter<DistributePersonBean>(this,
				distributer_auto, R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, final DistributePersonBean t) {
				holder.setText(R.id.state_name, t.getName());
				holder.setOnClickListener(R.id.state_name,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								det_repairer.doItemClick(t.getName(), t.getId());
							}
						});
			}
		};

		det_repairer.setOnItemClick(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DistributePersonBean distributePersonBean = (DistributePersonBean) parent
						.getAdapter().getItem(position);
				det_repairer.doListItemClick(distributePersonBean.getName(),
						distributePersonBean.getId());
			}
		});
		det_repairer.setAdapter(distributerAutoAdapter);
		det_repairer.setListAdapter(distributerAdapter);
		det_repairer.setHandler(repairerHandler);

		companyAdapter = new CommonAdapter<OwnerBean>(this, company_list,
				R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, OwnerBean t) {
				holder.setText(R.id.state_name, t.getCompany_name());
			}
		};

		companyAutoAdapter = new CommonAdapter<OwnerBean>(this, company_auto,
				R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, final OwnerBean t) {
				holder.setText(R.id.state_name, t.getCompany_name());
				holder.setOnClickListener(R.id.state_name,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								det_owner.doItemClick(t.getCompany_name(),
										t.getCompany_id() + "");
							}
						});
			}
		};

		det_owner.setOnItemClick(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				OwnerBean company = (OwnerBean) parent.getAdapter().getItem(
						position);
				det_owner.doListItemClick(company.getCompany_name(),
						company.getCompany_id() + "");
			}
		});
		det_owner.setAdapter(companyAutoAdapter);
		det_owner.setListAdapter(companyAdapter);
		det_owner.setHandler(ownerHandler);
	}

	void checkType() {

		Drawable tvWbDraw_normal = getResources().getDrawable(
				R.mipmap.icon_assign_wb_normal);
		tvWbDraw_normal.setBounds(0, 0, tvWbDraw_normal.getMinimumWidth(),
				tvWbDraw_normal.getMinimumHeight());
		tvCheckWb.setCompoundDrawables(null, tvWbDraw_normal, null, null);
		ivCheckWb.setImageResource(R.mipmap.icon_assign_point_normal);

		Drawable tvWxDraw_normal = getResources().getDrawable(
				R.mipmap.icon_assign_wx_normal);
		tvWxDraw_normal.setBounds(0, 0, tvWxDraw_normal.getMinimumWidth(),
				tvWxDraw_normal.getMinimumHeight());
		tvCheckWx.setCompoundDrawables(null, tvWxDraw_normal, null, null);
		ivCheckWx.setImageResource(R.mipmap.icon_assign_point_normal);

		if (type == 1) {
			Drawable tvWbDraw_on = getResources().getDrawable(
					R.mipmap.icon_assign_wb_on);
			tvWbDraw_on.setBounds(0, 0, tvWbDraw_on.getMinimumWidth(),
					tvWbDraw_on.getMinimumHeight());
			tvCheckWb.setCompoundDrawables(null, tvWbDraw_on, null, null);
			ivCheckWb.setImageResource(R.mipmap.icon_assign_point_on);

		} else {
			Drawable tvWxDraw_on = getResources().getDrawable(
					R.mipmap.icon_assign_wx_on);
			tvWxDraw_on.setBounds(0, 0, tvWxDraw_on.getMinimumWidth(),
					tvWxDraw_on.getMinimumHeight());
			tvCheckWx.setCompoundDrawables(null, tvWxDraw_on, null, null);
			ivCheckWx.setImageResource(R.mipmap.icon_assign_point_on);
		}
	}

	@OnClick({ R.id.tvBack, R.id.llWb, R.id.llWx, R.id.et_start, R.id.tvPost })
	public void onClick(View view) {
		DateChooseDialog.Builder builder;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.llWb:
			type = 1;
			checkType();
			break;
		case R.id.llWx:
			type = 2;
			checkType();
			break;
		case R.id.et_start:
			// 开始时间选择
			builder = new DateChooseDialog.Builder(this);
			builder.setTitle("选择日期");
			builder.setTextView((EditText) findViewById(R.id.et_start));
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							// 设置你的操作事项
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();
			break;
		case R.id.tvPost:
			if (CheckUtil.checkView(det_owner, et_start, det_repairer)) {
				doPost();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * @Fields repairerHandler : TODO(用于接受下拉组件返回的任务，如重新加载数据)
	 */
	Handler repairerHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case AppConfig.DET_RELOAD:
				getRepairerData(det_repairer.getText().toString());
				break;

			default:
				break;
			}
		};
	};

	/**
	 * @Fields ownerHandler : TODO(用于接受下拉组件返回的任务，如重新加载数据)
	 */
	Handler ownerHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case AppConfig.DET_RELOAD:
				getOwnerData(det_owner.getText().toString());
				break;

			default:
				break;
			}
		};
	};

	private void getOwnerData(String keyword) {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(keyword)) {
			params.put("keyword", keyword);
		}

		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_OWNER_LIST,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<OwnerBean> temp = new Gson().fromJson(
										data, new TypeToken<List<OwnerBean>>() {
										}.getType());
								// 填充数据
								company_list.clear();
								company_list.addAll(temp);
								companyAdapter.notifyDataSetChanged();
								company_auto.clear();
								company_auto.addAll(temp);
								companyAutoAdapter.notifyDataSetChanged();
								det_owner.isLoadData = true;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
					}
				});

	}

	private void getRepairerData(String keyword) {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(keyword)) {
			params.put("keyword", keyword);
		}

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_LEADER_REPAIRER_LIST, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<DistributePersonBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<DistributePersonBean>>() {
												}.getType());
								// 填充数据
								distributer_list.clear();
								distributer_list.addAll(temp);
								distributerAdapter.notifyDataSetChanged();
								distributer_auto.clear();
								distributer_auto.addAll(temp);
								distributerAutoAdapter.notifyDataSetChanged();
								det_repairer.isLoadData = true;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
					}
				});

	}

	void doPost() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("type", type + "");
		params.put("company_id", det_owner.getSelectedId());
		params.put("task_time", et_start.getText().toString());
		params.put("task_user_id", det_repairer.getSelectedId());
		params.put("remark", et_remark.getText().toString());

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_LEADER_ASSIGN,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								if (type == 1) {
									//跳转到维保
									Intent intent = new Intent(getContent(),LeaderMaintenanceTaskActivity.class);
									startActivity(intent);
								}
								else {
									//跳转到维修
									Intent intent = new Intent(getContent(),LeaderMaintenanceRepairListActivity.class);
									startActivity(intent);
								}
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg("派发失败");
					}
				});
	}
	
	Context getContent()
	{
		return this;
	}
}
